<template>
  <!-- 新增、编辑押金 -->
  <el-dialog
    v-el-drag-dialog
    :title="type === 'add' ? '新增押金单' : '押金编辑'"
    :visible.sync="visible"
    width="80%"
    append-to-body
    @closed="reset"
  >
    <!-- 客户信息 -->
    <div class="item">
      <div class="title">
        <span class="title-icon" />
        <span class="title-text">客户信息</span>
      </div>
      <el-form v-show="type === 'add'" class="form" label-position="right" label-width="85px">
        <el-form-item label-width="0" prop="qtype">
          <el-input v-model.trim="param" placeholder="请输入" clearable style="overflow: hidden;" @keyup.enter.native="searchMessage">
            <el-select slot="prepend" v-model="qtype" style="width: 100px;" placeholder="请选择">
              <el-option label="电话" value="csmRgPhone" />
              <el-option label="客户编号" value="csmCode" />
              <el-option label="身份证号" value="sfzh" />
            </el-select>
            <el-button slot="append" style="height: 33px;" class="append-search" @click="searchMessage">查询</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label-width="0">
          <div>
            <el-button @click="onClear">重置</el-button>
          </div>
        </el-form-item>
      </el-form>
      <p v-show="hasFirstDeposit && userInfo.showRN === JINJIANG" style="margin: -10px 0 10px 10px; color: red;">客户名下有押金未提瓶，无法再次交押金</p>
      <el-form ref="csmInfoFormCustomer" class="form" label-position="right" label-width="85px" :model="information" :rules="rules">
        <el-form-item label="客户编号:">
          <el-input v-model="temp.csmCode" disabled />
        </el-form-item>
        <el-form-item label="名称:">
          <el-input v-model="temp.csmName" disabled />
        </el-form-item>
        <el-form-item label="身份证号:">
          <el-input v-model="temp.sfzh" disabled />
        </el-form-item>
        <el-form-item label="联系电话:" prop="csmPhone">
          <el-select v-model="information.csmPhone" placeholder="请选择" clearable @change="changePhone">
            <el-option v-for="(v,index) in temp.phoneItems" :key="index" :label="v.csmPhone" :value="v.csmPhone" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系地址:" label-width="88px" style="width: calc(66% - 13px); margin-right: 10px;" prop="csmAddressId">
          <el-select v-model="information.csmAddressId" placeholder="请选择" clearable @change="changeAddress">
            <el-option v-for="(v,index) in temp.addressItems" :key="index" :label="v.csmAddress" :value="v.csmAddressId" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户类型:" prop="csmType">
          <el-input :value="formatColumnMap(customerTypeList, 'value', temp.csmType, 'desc')" disabled />
        </el-form-item>
        <el-form-item label="占用瓶数:" prop="csmType">
          <el-link v-if="temp.curGasCount" type="primary" :underline="false" style="margin-right: 0;" @click="openOccupy(temp)">{{ temp.curGasCount }}</el-link>
          <span v-else>{{ temp.curGasCount }}</span>
        </el-form-item>
      </el-form>
    </div>
    <!-- 押金信息 -->
    <div class="item">
      <div class="title">
        <span class="title-icon" />
        <span class="title-text">押金信息</span>
      </div>
      <el-form v-if="visible" ref="csmInfoForm" :model="submit" class="form" :rules="rules" label-position="right" label-width="100px">
        <el-form-item label="押金单号:" prop="depositCode">
          <el-input v-model="submit.depositCode" placeholder="请输入" :disabled="type === 'add' ? false : true" clearable style="overflow: hidden;" maxlength="10" minlength="6" @input="submit.depositCode=submit.depositCode.replace(/[\u4e00-\u9fa5]/ig, '')">
            <el-button v-if="type === 'add'" slot="append" class="append-search" style="height: 33px;" @click="getNum">获取</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="押瓶机构:" prop="ckOrgSNNo">
          <el-tree-select
            v-model="submit.ckOrgSNNo"
            :clearable="true"
            :disabled="type !== 'add'"
            class="tree-select"
            :popover-width="360"
            :select-params="{
              clearable: true,
              placeholder: '请选择押瓶机构',
            }"
            :tree-params=" {
              'expand-on-click-node': false,
              'highlight-current': true,
              'filterable': true,
              props:{
                value:'orgSNNo',
                label: 'orgName',
                disabled: 'disabled',
              },
              data: treeData
            }"
            @node-click="selectTreeChange"
          />
        </el-form-item>
        <el-form-item label="收款人:" prop="depReceiver">
          <el-select v-model="submit.depReceiver" placeholder="请选择">
            <el-option v-for="(v,userId) in depReceiver" :key="userId" :label="v.userName" :value="v.userName" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间:" prop="beginDt">
          <el-date-picker
            v-model="submit.beginDt"
            :disabled="(!!(corpSettingData.sp6 >> 11 & 0x01))&&type === 'add'"
            :type="(!!(corpSettingData.sp6 >> 11 & 0x01))?'month':'date'"
            :picker-options="type !== 'add'?pickerOptions1:{}"
            placeholder="选择日期"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="收款方式:" prop="calcType">
          <el-select v-model="submit.calcType" :disabled="type !== 'add'" placeholder="请选择" clearable>
            <el-option v-for="(v,index) in calcTypeList" :key="index" :label="v.desc" :value="v.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="手续费:">
          <el-input-number v-model="submit.fee1" :controls="false" :min="0" :max="99999" :precision="2" placeholder="请输入" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="收据单号:">
          <el-input v-model="submit.billCode" maxlength="30" />
        </el-form-item>
        <el-form-item label="押金来源:">
          <el-select ref="fromPlat " v-model="submit.fromPlat" placeholder="请选择" disabled>
            <el-option label="运气到家" :value="1" />
            <el-option label="微信公众号" :value="2" />
            <el-option label="支付宝小程序" :value="3" />
            <el-option label="好运气平台" :value="4" />
            <!-- <el-option label="CRM平台" :value="5" /> -->
            <el-option label="APP" :value="6" />
            <el-option label="微信小程序" :value="7" />
          </el-select>
        </el-form-item>
        <el-form-item label="支付方式:" prop="paymentMethod">
          <el-select v-model="submit.paymentMethod" placeholder="请选择" disabled>
            <el-option v-for="(v,index) in paymenFilList" :key="index" :label="v.desc" :value="v.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="押金照片信息:" label-width="110px" prop="" style="width: 100%;">
          <AddFileList
            :default-value="submit.depositrgPic"
            :item-attrs="{
              canEdit: true,
              __config__:{
                maxNumber:5,
                title:'附件上传'
              },
              prop: 'SysUserPage_imageUrl'
            }"
            @changeFormItem="uploadUrlChange"
          />
        </el-form-item>
        <el-form-item class="block" style="width: calc(100% - 10px); margin-right: 10px;">
          <label slot="label">备注:</label>
          <el-input v-model="submit.remark" type="textarea" :rows="2" maxlength="225" show-word-limit />
        </el-form-item>
      </el-form>
    </div>
    <!-- 押瓶信息 -->
    <div class="item">
      <div class="title">
        <span class="title-icon" />
        <span class="title-text">押瓶信息</span>
      </div>
      <el-form ref="bottleForm" :model="submit" :rules="rules" label-position="right" label-width="90px">
        <div style="display: flex;">
          <el-form-item label="经办人:" style="width: 33%;" prop="transactorId">
            <el-select v-model="submit.transactorId" placeholder="请选择" style="width: 100%;" @change="transactorIdChange">
              <el-option v-for="(v,userId) in depReceiver" :key="userId" :label="v.userName" :value="v.userId" />
            </el-select>
          </el-form-item>
          <el-form-item label="经办时间:" prop="transactDt" style="width: 33%; margin-left: 10px;">
            <el-date-picker
              v-model="submit.transactDt"
              style="width: 100%;"
              type="date"
              :clearable="false"
              placeholder="选择日期"
            />
          </el-form-item>
        </div>

        <div style="display: flex;">
          <el-form-item label="规格型号:" style="width: 33%;" prop="goodsName">
            <el-select ref="goodsName" v-model="gasTank.goodsName" style="width: 100%;" placeholder="请选择" clearable @change="getChange">
              <el-option v-for="(v,index) in gasTank" :key="index" :label="v.goodsName" :value="v.goodsId" />
            </el-select>
          </el-form-item>
          <el-form-item label-width="10px">
            <el-button type="primary" size="mini" @click="addDeposit">添加</el-button>
          </el-form-item>
        </div>

        <div v-for="(item,index) in tableData" :key="index" class="cardMain">
          <el-card class="card" style="margin-bottom: 8px;">
            <el-form sizi="mini" label-width="50px" class="form">
              <el-form-item label-width="80px" style="width: 300px;" label="规格型号:">
                {{ item.goodsName }}
              </el-form-item>
              <el-form-item label="数量:">
                <el-input-number v-model="item.goodsCount" :controls="false" size="mini" :min="1" :max="10000" :precision="0" style="width: 70px;" />
              </el-form-item>
              <el-form-item label="租金:">
                <el-input-number v-model="item.rental" :controls="false" size="mini" style="width: 90px;" :min="0" :max="10000" :precision="2" /> 元/个
              </el-form-item>
              <el-form-item size="mini" label="押金:">
                <el-input-number v-model="item.deposit" :controls="false" style="width: 90px;" :min="0" :max="2000" :precision="2" /> 元/个
              </el-form-item>
              <el-form-item label-width="80px" style="width: 200px;" label="押金合计:">
                {{ getsum(item,index) }}
              </el-form-item>
              <el-form-item label-width="80px" label="气瓶号:" style="width: 100%;">
                <el-tag
                  v-for="tag in item.btNoIDS"
                  :key="tag"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(tag,item)"
                >
                  {{ tag }}
                </el-tag>
                <el-input
                  ref="saveTagInput"
                  v-model.trim="item.inputValue"
                  class="input-new-tag"
                  maxlength="12"
                  size="mini"
                />
                <el-button type="primary" size="mini" @click="handleInputConfirm(item,index)">添加</el-button>
              </el-form-item>
            </el-form>
            <el-button class="del_Btn" type="danger" size="mini" icon="el-icon-delete" style="font-size: 14px;" @click="deleteDate(index)" />
          </el-card>
        </div>
        <!-- <el-form-item label="附件上传">
          <el-upload
            ref="upload"
            action="//upload.qiniup.com/"
            multiple
            :data="qiniuData"
            :before-upload="beforeUpload"
            :on-success="handleSuccess"
            :on-remove="handleRemove"
            :limit="limit"
            :on-exceed="handleExceed"
            :file-list="fileList"
            accept="image/jpeg, image/jpg, image/png"
          >
            <el-button icon="el-icon-upload2" size="small" type="primary" @click="pcUpload">点击上传</el-button>
          </el-upload>
        </el-form-item> -->
      </el-form>
    </div>

    <!-- <div>
      <el-image
        style="width: 100px; height: 100px;"
        :src="url"
        :preview-src-list="fileList"
      />
    </div> -->
    <div slot="footer" class="dialog-footer">
      <span class="deposit">押金总计：￥{{ AlltotalDeposit() }}</span>
      <el-checkbox v-model="isSeparate" class="depositForm">每个气瓶生成单独的押金单</el-checkbox>
      <el-button @click="visible = false">
        关闭
      </el-button>
      <el-button v-if="isBtn === 'toubao'" :loading="$loadingPlugin.insurance" type="primary" @click="insurance">
        客户投保
      </el-button>
      <el-button v-if="type === 'add' && userInfo.showRN === JINJIANG" :disabled="hasFirstDeposit" :loading="readOnly" type="primary" @click="saveAndPayOrder">
        话务下单
      </el-button>
      <el-button :loading="readOnly" type="primary" :disabled="hasFirstDeposit" @click="save">
        保存
      </el-button>
    </div>
    <receipt ref="receipt" />
    <insure ref="insure" />
    <chooseCsm ref="chooseCsm" />
    <occupy ref="occupy" />
  </el-dialog>
</template>

<script>
  import { mapGetters } from 'vuex'
  import {
    queryListCustomerExact,
    queryCodeGeneration,
    queryPayee,
    queryGasTankList,
    querySaveDepositList,
    queryMap,
    receiveOnAccount,
    depositOrgQueryList,
    checkFirstDepositStatus
  } from '@/api'
  import { queryQiniuyunUploadToken, querySaveUserAnnexListByPc } from '@/api'
  import Receipt from '../../customerCenter/depositManage/components/Receipt.vue'
  import Insure from '../../customerCenter/customerManage/components/Insure.vue'
  import ChooseCsm from './components/chooseCsm.vue'
  import AddFileList from './components/AddFileList.vue'
  import Occupy from '@/views/customerCenter/customerManage/components/Occupy.vue'
  import moment from 'dayjs'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import getTreeData from '@/utils/jsonTree'
  import dayjs from 'dayjs'
  import { formatColumnMap } from '@/utils'

  const JINJIANG = 58 // 晋江城市标识
  export default {
    name: 'normalr-eceipts-add',
    components: {
      Receipt,
      Insure,
      ChooseCsm,
      AddFileList,
      Occupy
    },
    data() {
      return {
        formatColumnMap,
        JINJIANG,
        readOnly: false,
        baseUrl: 'http://image.haoyunqi.com.cn/',
        calcTypeList: [],
        paymenFilList: [],
        treeData: [],
        id: '',
        limit: 1,
        token: '',
        information: {
          csmAddressId: '', // 地址id
          csmPhone: '' // 电话号码
        }, // 选择的联系人信息
        qiniuData: { // 这里是直接绑定data的值
          key: '', // 图片名字处理
          token: '', // 七牛云token
          data: {},
          bucket: ' '
        },
        annexList: [],

        type: 'add',
        isBtn: '',
        row: {},
        inputVisible: false,
        visible: false,
        isSeparate: false,
        fileList: [],
        depositDetails: [],
        totalDeposit: '',
        totalCount: '',
        tableData: [],
        goodsData: {}, // 商品
        i: 1,
        qtype: 'csmCode',
        param: '',
        phoneItems: [],
        addressItems: [],
        codeType: 9,
        depReceiver: [],
        gasTank: [],
        orgId: '',
        temp: {}, // 客户信息
        submit: {
          transactDt: new Date(), // 经办时间
          depositCode: '', // 押金单号
          depReceiver: '', // 收款人
          transactor: '', // 经办人
          transactorId: '', // 经办人id
          calcType: 3, // 收款方式
          remark: '',
          billCode: '', // 收据单号
          paymentMethod: 1, // 支付方式
          fee1: undefined, // 手续费
          beginDt: moment(new Date()).format(), // 开始时间
          ckOrgSNNo: '', // 压瓶机构
          fromPlat: 4, // 押金来源
          depositrgPic: ''
        },
        rules: {
          ckOrgSNNo: [{ required: true, message: '请选择押瓶机构', trigger: 'change' }],
          csmAddressId: [{ required: true, message: '请选择地址', trigger: 'change' }],
          depositCode: [{ required: true, message: '押金单号不能为空', trigger: 'change' }],
          beginDt: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
          calcType: [{ required: true, message: '请选择收款方式', trigger: 'change' }],
          paymentMethod: [{ required: true, message: '请选择支付方式', trigger: 'change' }],
          depReceiver: [{ required: true, message: '请选择收款人', trigger: 'change' }],
          transactorId: [{ required: true, message: '请选择经办人', trigger: 'change' }],
          transactDt: [{ required: true, message: '请选择经办时间', trigger: 'change' }]
        },
        hasFirstDeposit: false,
        customerTypeList: []
      }
    },
    computed: {
      ...mapGetters([
        'orgList',
        'userInfo',
        'corpSettingData',
        'csmCodeForPayOrder'
      ]),
      pickerOptions1() {
        const that = this
        const p = {
          disabledDate(time) {
            if (that.corpSettingData.sp6 >> 11 & 0x01) {
              const c = dayjs(time).format('YYYY-MM')
              const d = dayjs(that.temp.beginDt).format('YYYY-MM')
              const n = dayjs(new Date()).format('YYYY-MM')
              return (c !== d) && (c !== n)
            } else {
              return false
            }
          }
        }
        return p
      }
    },
    async created() {
      this.queryOptionsMap()
    },
    async mounted() {
      this.allNum()
    },
    methods: {
      // 获取所属机构数据
      async getTreeData() {
        const res = await depositOrgQueryList()
        if (res && res.data) {
          const data = res.data.map(item => ({
            label: item.orgName,
            ...item
          }))
          this.treeData = getTreeData(data)
        }
      },
      changePhone(val) {
        if (val) {
          var obj = this.temp.phoneItems.find(l => l.csmPhone === val)
          this.information.csmPhone = obj.csmPhone
        }
      },
      changeAddress(val) {
        if (val) {
          var obj = this.temp.addressItems.find(l => l.csmAddressId === val)
          if (obj.length > 0) {
            this.information.csmAddressId = obj.csmAddressId
          }
        }
      },

      async pcUpload() {
        if (this.fileList.length === 0) {
          this.$message.info('请选择文件')
          return
        }
        if (this.fileList.length > this.limit) {
          this.$message.error(`当前用户证件附件可继续上传最大张数：${this.limit}张`)
          return
        }
        const attList = this.fileList.map(item => {
          return {
            sourceName: item.response.key.split('.')[0],
            suffix: item.response.key.split('.')[1],
            url: item.response.key,
            size: item.response.fsize
          }
        })
        await querySaveUserAnnexListByPc({
          id: this.id,
          sysAttachmentList: attList
        })
      },
      beforeUpload(file) {
        const key = `${this.userInfo.corpCode}_${new Date().getTime()}_${file.name}`
        this.qiniuData.key = key
        return this.qiniuData
      },
      handleExceed(files, fileList) {
        this.$message.error(`当前用户证件附件可继续上传最大张数：${this.limit}张，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
      },
      handleSuccess(res, file, fileList) {
        this.fileList = fileList
      },
      handleRemove(file, fileList) {
        this.fileList = fileList
      },
      // 获取七牛云上传token
      async getQiniuyunUploadToken() {
        const res = await queryQiniuyunUploadToken()
        this.qiniuData.token = res.data
      },
      // 获取选中
      getChange(val) {
        if (val) {
          var goodsObj = {}
          this.gasTank.forEach((item) => {
            if (item.goodsId === val) {
              goodsObj = { ...item }
            }
          })
          this.goodsData = { // 商品
            depCode: this.submit.depositCode, // 押金单号
            goodsId: goodsObj.goodsId,
            goodsCode: goodsObj.goodsCode,
            goodsName: goodsObj.goodsName,
            deposit: goodsObj.ypFee1 ? (goodsObj.ypFee1 - 1) / 2 / 100 : (goodsObj.cashPledge ? goodsObj.cashPledge : 0),
            goodsCount: 1,
            totalDeposit: '',
            btNoIDS: [],
            rental: goodsObj.zpFee1 ? (goodsObj.zpFee1 - 1) / 2 / 100 : 0,
            specCode: goodsObj.specCode,
            specName: goodsObj.specName,
            // 上限下限校验参数
            maxYpFee: goodsObj.maxYpFee,
            maxZpFee: goodsObj.maxZpFee,
            minYpFee: goodsObj.minYpFee,
            minZpFee: goodsObj.minZpFee
          }
        } else {
          this.goodsData = {}
        }
      },
      // 计算价格
      getsum(item, index) {
        if (isNaN(item.goodsCount)) {
          return 0
        }
        item.totalDeposit = item.deposit * item.goodsCount
        return Number(item.totalDeposit).toFixed(2)
      },
      // 总数量
      allNum() {
        this.totalCount = this.depositDetails.reduce((num, item) => {
          return num + item.goodsCount
        }, 0)
        return this.totalCount
      },
      // 总押金
      AlltotalDeposit() {
        var num = 0
        this.tableData.forEach(l => {
          num = num + l.totalDeposit
        })
        return Number(num).toFixed(2)
      },
      // 添加押瓶信息
      addDeposit() {
        if (!this.submit.ckOrgSNNo) {
          this.$message.error('请选择押瓶机构!')
          return
        }
        if (!this.goodsData.goodsId) {
          this.$message.error('请选择规格!')
          return
        }
        var flag = this.tableData.findIndex(l => l.goodsId === this.goodsData.goodsId)
        if (flag >= 0) {
          this.tableData[flag].goodsCount++
          return
        }
        this.tableData.push({ ...this.goodsData })
      },
      // 删除押瓶信息
      deleteDate(index) {
        this.$confirm('确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        }).then((val) => {
          this.tableData.splice(index, 1)
          this.$message({ type: 'success', message: '删除成功!' })
        }).catch(() => {
          // this.$message({ type: 'info', message: '已取消删除' })
        })
      },

      // 删除气瓶号
      handleClose(tag, item) {
        item.btNoIDS.splice(item.btNoIDS.indexOf(tag), 1)
      },
      // 添加气瓶号
      handleInputConfirm(item, index) {
        const inputValue = item.inputValue
        if (!inputValue) return
        var num = item.btNoIDS.length
        var flag = item.btNoIDS.find(l => l === inputValue)
        if (flag) {
          this.$message.error('气瓶号不能重复添加')
          return
        }
        if (num >= item.goodsCount) {
          this.$confirm('瓶号数量和押瓶数量不一致，是否继续保存?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          }).then((val) => {
            item.btNoIDS.push(inputValue)
            item.inputValue = ''
          })
          return
        }
        item.btNoIDS.push(inputValue)
        item.inputValue = ''
      },
      // 收款人
      async payee(orgId) {
        const res = await queryPayee({ orgId })
        this.depReceiver = res.data
      },
      // 气瓶信息
      async gasTankList(orgId) {
        const res = await queryGasTankList({ orgId })
        // this.gasTank = res.data
        var list = []
        for (var i = 0; i < res.data.length; i++) {
          var goods = res.data[i]
          if ((goods.gdStatus & 1 << 2) > 0) {
            list.push(goods)
          }
        }
        this.gasTank = list
      },
      // 选择押瓶机构
      async selectTreeChange(value) {
        this.orgId = value.orgId
        this.submit.ckOrgSNNo = value.orgSNNo
        this.submit.ckOrgName = value.orgName
        this.submit.ckOrgId = value.orgId
        // 清空收款人 经办人
        this.submit.depReceiver = '' // 收款人
        this.submit.transactor = '' // 经办人
        this.submit.transactorId = '' // 经办人id
        await this.payee(value.orgId)
        await this.gasTankList(value.orgId)
        this.goodsData = {}
        this.tableData = []
      },
      async open(temp, type, btnTy, row) {
        await this.getTreeData()
        return new Promise(async resolve => {
          this.resolve = resolve
          this.submit.depReceiver = this.userInfo.userName
          this.submit.ckOrgSNNo = this.userInfo.orgSNNo
          this.submit.ckOrgName = this.userInfo.orgName
          this.submit.ckOrgId = this.userInfo.orgId
          this.submit.transactorId = this.userInfo.userId // 经办人
          this.submit.transactor = this.userInfo.userName // 经办人名称
          if (type === 'add') {
            // 默认填入部分信息
            this.getNum()
            this.temp = { ...temp }
            this.information.csmPhone = temp.csmRgPhone // 电话号码
            this.param = temp.csmCode
            this.qtype = 'csmCode'
            this.type = type
            this.gasTankList(this.userInfo.orgId)
            await this.payee(-1) // 收款人/经办人
            const isOrg = this.treeData.find(item => item.orgSNNo === this.userInfo.orgSNNo)
            if (!isOrg) {
              this.submit.ckOrgSNNo = ''
              this.submit.ckOrgName = ''
              this.submit.ckOrgId = ''
            }
          } else if (temp && type !== 'add') {
            console.log('编辑', temp)
            // this.qtype = 'csmCode'
            this.type = type
            this.isBtn = btnTy || ''
            this.row = row || {}
            this.param = temp.csmCode
            this.submit.depositCode = temp.depositCode ? temp.depositCode : '' // 押金单号
            this.submit.ckOrgSNNo = temp.ckOrgSNNo ? temp.ckOrgSNNo : '' // 押瓶机构
            this.submit.ckOrgName = temp.ckOrgName ? temp.ckOrgName : ''
            this.submit.ckOrgId = temp.ckOrgId ? temp.ckOrgId : ''
            this.submit.depReceiver = temp.depReceiver ? temp.depReceiver : '' // 收款人
            this.submit.beginDt = temp.beginDt ? temp.beginDt : '' // 开始时间
            this.submit.calcType = temp.calcType // 收款方式
            this.submit.fee1 = temp.fee1 ? temp.fee1 : '' // 手续费
            this.submit.remark = temp.remark ? temp.remark : ''
            this.submit.billCode = temp.billCode ? temp.billCode : '' // 收据单号
            this.submit.paymentMethod = temp.paymentMethod ? temp.paymentMethod : '' // 支付方式
            this.submit.transactorId = temp.transactorId ? temp.transactorId : '' // 经办人
            this.submit.transactor = temp.transactor ? temp.transactor : '' // 经办人名称
            this.submit.transactDt = temp.transactDt ? temp.transactDt : moment() // 经办时间
            this.submit.fromPlat = temp.fromPlat ? temp.fromPlat : ''
            this.submit.depositrgPic = temp.depositrgPic
            // 气瓶列表
            if (temp.depositDetails) {
              temp.depositDetails.map(l => {
                this.tableData.push({
                  depCode: l.depCode, // 押金单号
                  goodsId: l.goodsId,
                  goodsCode: l.goodsCode,
                  goodsName: l.goodsName,
                  deposit: l.deposit,
                  goodsCount: l.goodsCount,
                  totalDeposit: l.totalDeposit,
                  btNoIDS: l.btNoIDS ? l.btNoIDS.split(',') : [],
                  rental: l.rental,
                  specCode: l.specCode,
                  specName: l.specName,
                  // 上限下限校验参数
                  maxYpFee: l.maxYpFee,
                  maxZpFee: l.maxZpFee,
                  minYpFee: l.minYpFee,
                  minZpFee: l.minZpFee
                })
              })
            }
            // // 处理默认电话
            if (temp.phoneItems.length && temp.csmRgPhone) {
              const obj = temp.phoneItems.filter(l => l.csmPhone === temp.csmRgPhone)
              if (obj.length) {
                this.information.csmPhone = obj[0].csmPhone
              }
            }
            // 处理默认地址
            if (temp.addressItems.length && temp.csmAddressId) {
              const obj = temp.addressItems.filter(l => l.csmAddressId === temp.csmAddressId)
              if (obj.length > 0) {
                this.information.csmAddressId = obj[0].csmAddressId
              }
            }
            this.temp = { ...temp }
            // 查询规格型号
            if (temp.ckOrgId) {
              this.gasTankList(temp.ckOrgId)
              await this.payee(temp.ckOrgId) // 收款人/经办人
            }
          } else {
            this.qtype = 'csmCode'
          }
          // 过滤支付方式
          let arr = ['现金', '微信支付', '支付宝', '门店扫码']
          if (this.type === 'add') {
            arr = ['现金']
          }
          this.paymentMethodList.filter(item => {
            if (arr.includes(item.desc)) {
              this.paymenFilList.push(item)
            }
          })
          this.visible = true
        })
      },
      // 查询客户信息
      async searchMessage() {
        if (!this.param) {
          this.$message({
            message: '查询条件不能为空',
            type: 'error'
          })
          return
        }
        // this.$refs.csmInfoForm.resetFields()
        this.$refs.csmInfoFormCustomer.resetFields()
        this.$refs.bottleForm.resetFields()
        const params = {}
        params[this.qtype] = this.param
        const res = await queryListCustomerExact(params)
        if (!res.data || res.data.length === 0) {
          this.$message.error('未搜索到该客户信息')
          return
        }
        const result = { data: {}}
        if (res.data.length > 1) {
          const data = await this.$refs.chooseCsm.open(res.data)
          console.log('data', data)
          result.data = data
        } else {
          result.data = res.data[0]
        }
        // 处理默认电话
        if (result.data.phoneItems.length) {
          const obj = result.data.phoneItems.find(l => l.isMain === 1)
          if (obj) this.information.csmPhone = obj.csmPhone
        }
        // 处理默认地址
        if (result.data.addressItems.length) {
          const obj = result.data.addressItems.find(l => l.isMain === 1)
          if (obj) this.information.csmAddressId = obj.csmAddressId
        }
        // 客户信息
        this.temp = result.data
        if (this.userInfo.showRN === JINJIANG) {
          const res1 = await checkFirstDepositStatus({ csmId: this.temp.csmId })
          this.hasFirstDeposit = res1.data === 1
        }
      },
      // 获取单号
      async getNum() {
        const codeType = this.codeType
        const code = {
          codeType
        }
        const result = await queryCodeGeneration(code)
        this.submit.depositCode = result.data
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2, res3] = await Promise.all([mergeAsyncFunc(receiveOnAccount, {}), mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' }), mergeAsyncFunc(queryMap, { enumName: 'CustomerType' })])
        this.calcTypeList = res1.data // 收款方式
        this.paymentMethodList = res2.data // 支付方式
        this.customerTypeList = res3.data // 客户类型
      },
      // 保存
      async save() {
        return new Promise((resolve, reject) => {
          this.readOnly = true
          if (!this.submit.ckOrgSNNo) {
            this.$message.error('请选择押瓶机构!')
            this.readOnly = false
            return reject()
          }
          Promise.all([this.$refs.csmInfoFormCustomer && this.$refs.csmInfoFormCustomer.validate(), this.$refs.csmInfoForm && this.$refs.csmInfoForm.validate(), this.$refs.bottleForm && this.$refs.bottleForm.validate()]).then(async(res) => {
            if (res && res.every(item => item)) {
              if (this.tableData.length === 0) {
                this.$message.error('请选择气瓶型号')
                this.readOnly = false
                return reject('请选择气瓶型号')
              }
              for (var i = 0; i < this.tableData.length; i++) {
                var row = this.tableData[i]
                if (!Number(row.goodsCount) || Number(row.goodsCount) <= 0) {
                  this.readOnly = false
                  this.$message.error(`请输入${row.goodsName}的数量`)
                  return reject()
                }
                if (row.maxYpFee) {
                  var maxYpFee = (row.maxYpFee - 1) / 2 / 100
                  if ((row.deposit * 1) > maxYpFee) {
                    this.readOnly = false
                    this.$message.error(`${row.goodsName}押金不能大于上限`)
                    return reject()
                  }
                }

                if (row.minYpFee) {
                  var minYpFee = (row.minYpFee - 1) / 2 / 100
                  if (row.deposit < minYpFee) {
                    this.readOnly = false
                    this.$message.error(`${row.goodsName}押金不能小于下限`)
                    return reject()
                  }
                }

                if (row.maxZpFee) {
                  var maxZpFee = (row.maxZpFee - 1) / 2 / 100
                  if (row.rental > maxZpFee) {
                    this.readOnly = false
                    this.$message.error(`${row.goodsName}租金不能大于上限`)
                    return reject()
                  }
                }

                if (row.minZpFee) {
                  var minZpFee = (row.minZpFee - 1) / 2 / 100
                  if (row.rental < minZpFee) {
                    this.readOnly = false
                    this.$message.error(`${row.goodsName}租金不能小于下限`)
                    return reject()
                  }
                }
              }
              // 处理地址
              var obj = this.temp.addressItems.find(l => l.csmAddressId === this.information.csmAddressId)
              var depositDetails = JSON.parse(JSON.stringify(this.tableData))
              var num = 0 // 总数量
              depositDetails.forEach(l => {
                l.btNoIDS = l.btNoIDS.join(',')
                num = num + l.goodsCount
                l.depCode = this.submit.depositCode // 押金单号
                delete l.maxYpFee
                delete l.maxZpFee
                delete l.minYpFee
                delete l.minZpFee
              })
              depositDetails = [...depositDetails]
              const params = {
                // 客户信息
                csmName: this.temp.csmName,
                csmCardNo: this.temp.sfzh, // 身份证
                csmAddress: obj.csmAddress, // 地址名称
                isSeparate: Boolean(this.isSeparate), // 单独押金单
                csmCode: this.temp.csmCode, // 客户编号
                csmId: this.temp.csmId,
                ...this.submit,
                ...this.information,
                beginDt: moment(this.submit.beginDt).format(), // 开始时间
                transactDt: moment(this.submit.transactDt).format(), // 经办时间
                depositId: this.type === 'add' ? 0 : this.temp.depositId,
                depositDetails,
                totalCount: num, // 总数量
                totalDeposit: this.AlltotalDeposit(), // 押金合计
                depStatus: 0 // 押金单审核状态 2表示新增押金单不需要审核
              }
              const res = await querySaveDepositList(params)
              if (res.status === 200) {
                this.$message({
                  title: '提示',
                  message: '保存成功',
                  type: 'success',
                  duration: 2000
                })
                // 更新列表数据
                this.visible = false
                this.$emit('upDataTable')
                this.readOnly = false
                // 判断支付方式（如果当选择现金支付时，保存提交信息后无需再跳转到扫码付款页面；）
                if (params.paymentMethod !== 1) {
                  // 支付页面
                  await this.$refs.receipt.open(params)
                }
              }
            } else {
              this.readOnly = false
            }
            resolve()
          }).catch(() => {
            this.readOnly = false
            reject()
          })
        })
      },
      // 话务下单
      async saveAndPayOrder() {
        this.$confirm('是否保存押金信息？', '提示', {
          confirmButtonText: '保存',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          await this.save()
          await this.$store.dispatch('payOrder/setCsmCodeForPayOrder', this.temp.csmCode)
          this.$router.push('/salesService/phoneOrder')
          this.visible = false
        })
      },
      async add() {
        this.resolve()
        this.visible = false
        this.$message({
          title: '提示',
          message: '新增成功',
          type: 'success',
          duration: 2000
        })
      },
      async edit() {
        this.resolve(this.temp)
        this.visible = false
        this.$message({
          title: '提示',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
      },
      uploadUrlChange(e) {
        console.log(e)
        this.submit.depositrgPic = e.url
      },
      // 重置
      onClear() {
        this.param = ''
        this.temp.csmCode = ''
        this.temp.csmName = ''
        this.temp.sfzh = ''
        this.information.csmPhone = ''
        this.temp.phoneItems = []
        this.information.csmAddressId = ''
        this.temp.addressItems = []
      },
      // 客户投保
      async insurance() {
        await this.$refs.insure.open(this.row)
      },
      // 处理经办人入参数据
      transactorIdChange(val) {
        const arr = this.depReceiver.filter(l => l.userId === val)
        this.submit.transactor = arr[0].userName
        this.submit.transactorId = arr[0].userId
      },
      reset() {
        this.$nextTick(() => {
          this.hasFirstDeposit = false
          this.id = ''
          this.limit = 1
          this.token = ''
          this.information = {
            csmAddressId: '', // 地址id
            csmPhone: '' // 电话号码
          } // 选择的联系人信息
          this.qiniuData = { // 这里是直接绑定data的值
            key: '', // 图片名字处理
            token: '', // 七牛云token
            data: {},
            bucket: ' '
          }
          this.annexList = []
          this.type = 'add'
          this.isBtn = ''
          this.row = {}
          this.inputVisible = false
          this.visible = false
          this.isSeparate = false
          this.fileList = []
          this.depositDetails = []
          this.totalDeposit = ''
          this.totalCount = ''
          this.tableData = []
          this.goodsData = {}
          this.i = 1
          this.qtype = 'csmRgPhone'
          this.param = ''
          this.phoneItems = []
          this.addressItems = []
          this.codeType = 9
          this.depReceiver = []
          this.gasTank = []
          this.orgId = ''
          this.temp = {}
          this.submit = {
            transactDt: new Date(), // 经办时间
            depositCode: '', // 押金单号
            depReceiver: '', // 收款人
            transactor: '', // 经办人
            transactorId: '', // 经办人id
            calcType: 3, // 收款方式
            remark: '',
            billCode: '', // 收据单号
            paymentMethod: 1, // 支付方式
            fee1: undefined, // 手续费
            beginDt: moment(new Date()).format(), // 开始时间
            ckOrgSNNo: '', // 压瓶机构
            ckOrgName: '',
            ckOrgId: '',
            fromPlat: 4,
            depositrgPic: ''
          }
          // this.$refs.csmInfoForm.resetFields()
          this.$refs.csmInfoFormCustomer.resetFields()
          this.$refs.bottleForm.resetFields()
        })
      },
      // 格式化金额
      formatInput(e) {
        if (e.target.value) {
          this.submit.fee1 = (e.target.value * 1).toFixed(2)
        }
      },
      // 格式化金额
      onInput(value) {
        const res = value
          .replace(/[^\d.]/g, '')
          .replace(/\.{2,}/g, '.')
          .replace(/^\./g, '')
          .replace('.', '$#$')
          .replace(/\./g, '')
          .replace('$#$', '.')
          .replace(/^0\d+|^\./g, '')
          .replace(/^(.*\..{2}).*$/, '$1')
        this.submit.fee1 = res
      },
      // 格式化租金
      onInputRental(val, item, type) {
        const res = val
          .replace(/[^\d.]/g, '')
          .replace(/\.{2,}/g, '.')
          .replace(/^\./g, '')
          .replace('.', '$#$')
          .replace(/\./g, '')
          .replace('$#$', '.')
          .replace(/^0\d+|^\./g, '')
          .replace(/^(.*\..{2}).*$/, '$1')
        const val1 = res
        this.$set(item, type, val1)
      },
      // 格式化租金
      formatInputRental(e) {
        if (e.target.value) {
          e.target.value = (e.target.value * 1).toFixed(2)
        }
      },
      // 占用瓶
      async openOccupy(row) {
        await this.$refs.occupy.open(row)
      }
    }
  }
</script>

<style lang="scss" scoped>
.item {
  margin: 0 20px 20px 20px;
  margin-bottom: 20px;
  .title {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    .title-icon {
      display: inline-block;
      width: 4px;
      height: 18px;
      margin-right: 6px;
      background: #01999f;
    }
    .title-text {
      font-family: Microsoft YaHei, Microsoft YaHei-Bold;
      font-size: 14px;
      font-weight: 700;
      color: #01999f;
    }
    .content {
      margin-bottom: 0;
    }
  }
  &:last-child {
    margin-bottom: 0;
  }
  .card {
    position: relative;

    .del_Btn {
      position: absolute;
      top: 0;
      right: 0;
      width: 44px;
      height: 40px;
    }
  }
}

.form {
  display: flex;
  flex-wrap: wrap;
  // justify-content: space-between;
  & /deep/ .el-form-item {
    width: calc(33% - 10px);
    margin-left: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
}

.dialog-footer {
  .deposit {
    float: left;
    margin-left: 30px;
    font-size: 16px;
    font-weight: 700;
    color: #F26A24;
  }

  .depositForm {
    float: left;
    margin-left: 160px;
    font-size: 14px;
    color: #01999F;
  }
}

.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  // height: 32px;
  // line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
  margin-left: 10px;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.cardMain {
  & /deep/ .el-form-item {
    width: auto;
  }
  /deep/ .el-card__body {
    padding: 5px;
  }
}

</style>
